import React, { PureComponent,Fragment } from 'react';
import { connect } from '@@/plugin-dva/exports';
import styles from './index.less';
import Cookie from '@/utils/cookie.js';
import u291 from './img/u291.png';
import u325 from "./img/u325.png";
import u510 from "./img/u510.png";
import u311 from "./img/u311.png";
import u318 from "./img/u318.png";
import u312 from "./img/u312.png";
import tx from "./img/tx.png";
import u298 from "./img/u298.svg";
import u302 from "./img/u302.png";
import u301 from "./img/u301.png";
import IndexManage from "./img/indexManage.png";
import { Tooltip } from "antd";
import { history } from 'umi';
import UserFeedBack from "@/pages/HomePage/UserFeedback/index";
import {stopRequest} from "@/utils/requsetApi";
class LeftTooltip extends PureComponent {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      userImg: false,
      manageImg: false,
      indexImg: false,
      openModel: false,
      value: '', // 首页输入框内容
      userId: Cookie.get('userName'),
      token: Cookie.get('token'),
      pageList:{
        "维度管理":{
          url:"/manager/DimensionManagement",
          id:"4028808690ac98930190aca1ed8c0005"
        },
        "维值管理": {
          url:"/manager/DimensionValueManagement",
          id:"4028808690ac98930190aca1f5c80006"
        },
        "基础指标管理": {
          url:"/manager/BasicIndexManagement",
          id:"4028808690ac98930190aca1e5930004"
        },
        "用户管理": {
          url:"/manager/UserManage",
          id:"userPage"
        },
        "角色管理": {
          url:"/manager/RoleManage",
          id:"rolePage"
        },
        "指标管理": {
          url:"/manager/IndexManagement",
          id:"indexManagement"
        },
        "用户明细": {
          url:"/manager/UserDetail",
          id:"userDetail"
        },
      },
    }
  }

  //初始化
  componentDidMount() {
    const { userId } = this.state;
    const { dispatch } = this.props;
    const cudsToken = this.getQueryStringData("cudsToken");
    if(cudsToken){
      dispatch({
        type: 'login/checkToken',
        payload: {
          cudsToken,
        },
        callback: (res) => {
          if (res?.data?.token) {
            if (Cookie.get('token')) Cookie.del('token');
            if (Cookie.get('userName')) Cookie.del('userName');
            Cookie.set('token', res.data.token);
            Cookie.set('userName', res.data.username);
            const urlUserId = res.data.username;
            if(urlUserId){
              this.setState({userId:urlUserId})
            }
            // 待定tenantId 放哪里
            const  tenantId = res.data?.tenantId||""
            dispatch({
              type: 'login/getAuthList',
            })
            dispatch({
              type:"intellectAssistant/updateState",
              payload:{
                tenantId:tenantId
              }
            })
          }
        },
      });
    }else {
      dispatch({
        type:"intellectAssistant/updateState",
        payload:{
          tenantId:""
        }
      })
    }
  }




  //页面对话更新时定位到底部
  componentDidUpdate(prevProps, prevState) {
  }
  getQueryStringData=(name = "all")=> {
    const queryString = window.location.search.substring(1);
    if (queryString !== "") {
      const objAll = {};
      const vars = queryString.split("&");
      for (let i = 0; i < vars.length; i++) {
        const pair = vars[i].split("=");
        if (name === "all") {
          objAll[pair[0]] = pair[1];
        } else if (pair[0] === name) {
          return pair[1];
        }
      }
      return Object.keys(objAll).length === 0 ? "" : objAll;
    }
    return "";
  }

  toHistory = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'intellectAssistant/updateState',
      payload:{
        title:"新会话",
        dialogueId:"",
        messageList: [],
        checkedSwitch:false,
        pageContent:[],
        backMessageListGz:[],
        backMessageListAI:[],
        dialogFlag:"0",
        isLoading:false,
        titleGz:"新会话",
        titleAI:"新会话",
        dialogueIdGz:"",
        dialogueIdAI:"",
        pageFileList:[],
      }
    })
    history.push({
      pathname: '/history',
    });
  };

  toHomePage = () => {
    const { dispatch } = this.props;
    stopRequest();
    dispatch({
      type: 'intellectAssistant/updateState',
      payload: {
        isLoading: false,
      }
    });
    dispatch({
      type: 'intellectAssistant/updateState',
      payload:{
        title:"新会话",
        dialogueId:"",
        messageList: [],
        checkedSwitch:false,
        pageContent:[],
        backMessageListGz:[],
        backMessageListAI:[],
        dialogFlag:"0",
        isLoading:false,
        titleGz:"新会话",
        titleAI:"新会话",
        dialogueIdGz:"",
        dialogueIdAI:"",
        pageFileList:[],
      }
    })
    history.push({
      pathname: '/homePage',
    });
  };

  onClickLogout = ()=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'intellectAssistant/updateState',
      payload:{
        title:"新会话",
        dialogueId:"",
        messageList: []
      }
    })
    dispatch({
      type: 'login/logout',
    });
  }

  clickUser = () => {
    this.setState({
      userImg: !this.state.userImg,
      manageImg: false,
      indexImg: false,
    })
  }
  clickManage = () => {
    const {userId} = this.state;
    if(window.location.pathname!=='/login' && !userId){
      history.push({
        pathname: '/login',
      });
    } else {
      this.setState({
        manageImg: !this.state.manageImg,
        userImg: false,
        indexImg: false,
      })
    }
  }
  clickIndex = () => {
    const {userId} = this.state;
    if(window.location.pathname!=='/login' && !userId){
      history.push({
        pathname: '/login',
      });
    } else {
      this.setState({
        indexImg: !this.state.indexImg,
        manageImg: false,
        userImg: false,
      })
    }
  }
  handelOk = () => {
    this.setState({openModel: true})
  }

  submitFeedback = (feedbackText)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'intellectAssistant/fetchFeedBack',
      payload: {
        question:'',
        answer:'',
        islike:'',
        feedback:feedbackText,
      },
      callback: () => {
        this.setState({
          msgVisible:false,
          type:""
        });
      },
    });
  }

  handelCancel = () => {
    this.setState({openModel: false})
  }



  jumpNew=()=>{
    const {userId} = this.state;
    const {dialogFlag,dispatch} =this.props;
    stopRequest();
    dispatch({
      type: 'intellectAssistant/updateState',
      payload: {
        isLoading: false,
      }
    });
    if(window.location.pathname!=='/login' && !userId){
      history.push({
        pathname: '/login',
      });
    } else {
      const {dispatch} = this.props;
      history.push({
        pathname: '/newTalk'
      })
      let payload = {
        dialogueId: "",
        title:"新会话",
        messageList: [],
        [dialogFlag==="0"?"backMessageListGz":"backMessageListAI"]:[],
        [dialogFlag==="0"?"titleGz":"titleAI"]:"新会话",
        [dialogFlag==="0"?"dialogueIdGz":"dialogueIdAI"]:"",
      }
      if(dialogFlag==="1") {
        payload.pageContent=[]
        payload.pageFileList=[]
      }
      dispatch({
        type: 'intellectAssistant/updateState',
        payload: {
          ...payload
        }
      });
    }
  }
   toManagement = (name)=>{
     const { pageList } =this.state
     if(name==="指标知识图谱") {
       return window.open("http://10.177.16.199:8003/browser/")
     }
     const userId= Cookie.get('userName');
     const  token= Cookie.get('token');
     let  nowTime = Date.now()
     const iframe= pageList[name].url+"?token="+token+"&id="+pageList[name].id+"&userId="+userId+"&time="+nowTime;
     window.open(iframe)
  }
  manageEng=()=>{
    this.setState({
      userImg: false,
      manageImg: true,
      indexImg: false,
    })
  }
  manageLeve=()=>{
    this.setState({
      userImg: false,
      manageImg: false,
      indexImg: false,
    })
  }
  userEng=()=>{
    this.setState({
      userImg: true,
      manageImg: false,
      indexImg: false,
    })
  }
  userLeve=()=>{
    this.setState({
      userImg: false,
      manageImg: false,
      indexImg: false,
    })
  }
  indexEng=()=>{
    this.setState({
      userImg: false,
      manageImg: false,
      indexImg: true,
    })
  }
  indexLeve=()=>{
    this.setState({
      userImg: false,
      manageImg: false,
      indexImg: false,
    })
  }
  render() {
    const {openModel,userImg,userId,manageImg,indexImg} =this.state
    const authList = localStorage.getItem("authList")&&JSON.parse(localStorage.getItem("authList"))||this.props.authList;
    const manageList = authList?.length>0&&authList.filter((item)=>{
       return  item.value.includes("Management")&&!item.value.includes(":")&&item.value!=="indexManagement"
    })||[]
    const useList = authList?.length>0&&authList.filter((item)=>{
      return item.value==="userManage"||item.value==="roleManage"||item.value==="userDetail"
    })||[]
    const indexPageList = authList?.length>0&&authList.filter((item)=>{
      return item.value==="indexManagement"
    })||[]
    return (
      <Fragment>
        <div className={styles.rightIcon}>
          <Tooltip placement="right" title={'回到首页'}>
            <img className={styles.icon0} src={u291} alt="" onClick={this.toHomePage}/>
          </Tooltip>
          <img className={styles.icon2} src={u298} alt=""/>
          <Tooltip placement="right" title={'开启新会话'}>
            <img onClick={this.jumpNew} className={styles.icon3} src={u318} alt=""/>
          </Tooltip>
          <Tooltip placement="right" title={'历史会话'}>
            <img className={styles.icon1} src={u312} alt="" onClick={this.toHistory}/>
          </Tooltip>
          <Tooltip placement="right" title={'知识管理'}>
            <img className={styles.icon1} src={u311} alt="" onClick={this.clickManage}/>
          </Tooltip>
          <Tooltip placement="right" title={'指标管理'}>
            <img className={styles.icon11} src={IndexManage} alt="" onClick={this.clickIndex}/>
          </Tooltip>
          <img className={styles.icon2} src={u298} alt=""/>
          <img className={styles.icon3} src={tx} alt="" onClick={this.clickUser}/>
          <img className={styles.icon1} src={u301} alt=""/>
        </div>
        {manageImg ?
          <div className={styles.rightIconUser} onMouseEnter={this.manageEng} onMouseLeave={this.manageLeve}>
            {manageList.map((item, index) => {
              return <div key={index} className={styles.feedBack} onClick={() => this.toManagement(item.label)}>{item.label}</div>
            })}
          </div> : null}
        {indexImg ?
          <div className={styles.rightIconUser} style={{top:"55%"}} onMouseEnter={this.indexEng} onMouseLeave={this.indexLeve}>
            {indexPageList.map((item, index) => {
              return <div key={index} className={styles.feedBack} onClick={() => this.toManagement(item.label)}>{item.label}</div>
            })}
          </div> : null}
        {userImg ?
          <div className={styles.rightIconUser} onMouseEnter={this.userEng} onMouseLeave={this.userLeve}>
            <div className={styles.number}>{userId}</div>
            {useList.map((item, index) => {
              return <div key={index} className={styles.feedBack} onClick={() => this.toManagement(item.label)}>{item.label}</div>
            })}
            <div className={styles.feedBack} onClick={this.handelOk}>用户反馈</div>
            <div className={styles.img}></div>
            <div className={styles.feedBack} onClick={this.onClickLogout}>退出登录</div>
          </div> : null}
        <UserFeedBack
          openModel={openModel}
          handelOk={this.handelOk}
          handelCancel={this.handelCancel}
          submitFeedback={this.submitFeedback}/>
      </Fragment>
    );
  }
}

//这里的bonceChatGpt 是创建models时取的model名   namespace："这里的bonceChatGpt"  umi会自动识别该字段进行如下解构
export default connect(({intellectAssistant,login}) => ({
  dialogFlag: intellectAssistant.dialogFlag,
  authList: login.authList,
}))(LeftTooltip);
